import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Button } from 'antd';
import PropTypes from 'prop-types';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import HandleModel from './handleModel';
import ExportModal from './exportModel';
import { filterAuth } from '@/support/common';
import ConfirmDelModal from './confirmDelModal';
import { downloadFileByUrl } from '@/utils';
import moment from 'moment';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  ControlBoxMng: state.ControlBoxMng,
  loading: state.loading.models['ControlBoxMng'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});
class ControlBoxMng extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      formData: {},
      exportVisible: false,
      checkRecord: {},
      confirmVisible: false,
      templateFileUrl: '',
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'ControlBoxMng/getFetchPage',
      payload: {
        url: '/msalcohollock/cbox/page',
        ...formValues,
      },
    });
    this.props.dispatch({
      type: 'electricFenceMng/getData',
      payload: { url: '/common/template/detail', templateCode: 'circleFenceImport' },
      callback: res => {
        this.setState({ templateFileUrl: res.data ? res.data.templateUrl : null });
      },
    });
  }
  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
    });
  };
  //  新增
  handleAdd = () => {
    this.setState({
      modalVisible: true,
      formData: {},
    });
  };

  //  编辑
  handleEdit = (record: any) => {
    this.setState({
      modalVisible: true,
      formData: record,
    });
  };
  closeModal = () => {
    this.setState({
      modalVisible: false,
      formData: {},
    });
  };
  //批量导入
  handleExport = () => {
    this.setState({
      exportVisible: true,
    });
  };
  closeExportModal = () => {
    this.setState({
      exportVisible: false,
    });
  };
  handleFreshPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'ControlBoxMng/getFetchPage',
      payload: {
        url: '/msalcohollock/cbox/page',
        ...formValues,
      },
    });
  };

  //  删除
  handleDelete = (record: any) => {
    //先对绑定状态进行查询，未绑定才能弹出二次确认框弹窗进行删除
    const { dispatch } = this.props;
    dispatch({
      type: 'ControlBoxMng/getData',
      payload: { url: `/msalcohollock/cbox/binding/state/${record.code}` },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            confirmVisible: true,
            checkRecord: record,
          });
          // this.handleFreshPage()
        } else {
          message.error('控制盒已绑定车辆，解绑后才可删除');
        }
      },
    });
  };
  closeConfirmModal = (ref = false) => {
    this.setState({
      confirmVisible: false,
      checkRecord: {},
    });
    if (ref) {
      this.handleFreshPage();
    }
  };
  render() {
    const {
      ControlBoxMng: {
        pageData: { list, pagination },
      },
      loading,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const {
      formValues,
      modalVisible,
      formData,
      exportVisible,
      checkRecord,
      confirmVisible,
      templateFileUrl,
    } = this.state;
    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    };

    const searchItems = [
      {
        title: '控制盒编号',
        type: 'input',
        key: 'code',
        maxLength: 50,
        rules: [
          {
            required: false,
            message: '请输入英文及数字!',
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
      },
      {
        title: '设备名称',
        type: 'input',
        key: 'name',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入中英文及数字、特殊字符!' ,
            // pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            message: '不能输入空字符!',
            pattern: /^\S+$/,
          },
        ],
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => <span>共&nbsp;{page?.total}&nbsp;条</span>,
    };

    const columns = [
      {
        title: '控制盒编号',
        dataIndex: 'code',
      },
      {
        title: '控制盒名称',
        dataIndex: 'name',
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '产品序列号',
        dataIndex: 'seriesNumber',
      },
      {
        title: 'LTE模块IMEI号',
        dataIndex: 'lteImeiNumber',
      },
      {
        title: 'Sim卡串号',
        dataIndex: 'simImeiNumber',
        render(val: any) {
          return <MaskText text={val} type="simCard" />;
        },
      },
      {
        title: '硬件版本号',
        dataIndex: 'hardwareVersion',
      },
      {
        title: '软件版本号',
        dataIndex: 'softwareVersion',
      },
      {
        title: '控制盒错误码',
        dataIndex: 'errorCode',
      },
      {
        title: '数据采集时间',
        dataIndex: 'collectTime',
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'controlBoxMng_doEdit',
              onConfirm: () => {
                this.handleEdit(record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'controlBoxMng_doDel',
              onConfirm: () => {
                this.handleDelete(record);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'ControlBoxMng/getFetchPage',
              url: '/msalcohollock/cbox/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {filterAuth('controlBoxMng_doAdd', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleAdd}>
                新增控制盒
              </Button>
            ) : null}
            {filterAuth('controlBoxMng_doExport', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleExport}>
                批量导入
              </Button>
            ) : null}
          </div>
          <PateoTable
            extraHandle={true}
            currentName={'page'}
            pageSizeName={'size'}
            tableProps={tableProps}
            fetchParams={{ type: 'ControlBoxMng/getFetchPage', url: '/msalcohollock/cbox/page' }}
            formValues={formValues}
          />
        </Card>
        <HandleModel
          modalVisible={modalVisible}
          formData={formData}
          closeModal={this.closeModal}
          freshPage={this.handleFreshPage}
        ></HandleModel>
        <ExportModal
          modalVisible={exportVisible}
          closeModal={this.closeExportModal}
          freshPage={this.handleFreshPage}
        ></ExportModal>
        <ConfirmDelModal
          record={checkRecord}
          modalVisible={confirmVisible}
          closeModal={this.closeConfirmModal}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(ControlBoxMng);
